package org.changs.nav.delegate.amap;

import android.content.Context;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

/**
 * Created by yincs on 2017/10/17.
 */

public class AmapTipHelper {

    private final Context mContext;
    private Disposable subscribe;

    @Inject
    public AmapTipHelper(Context context) {
        this.mContext = context;
    }

    public void query(String key, OnTipsListener listener) {
        query(key, "深圳", listener);
    }

    public void query(String key, String city, OnTipsListener listener) {
        Timber.d("query() called with: key = [" + key + "], city = [" + city + "], listener = [" + listener + "], Thread = "+Thread.currentThread().getName());
        stop();
        subscribe = Observable
                .fromCallable((Callable<List<Tip>>) () -> {
                    InputtipsQuery inputQuery = new InputtipsQuery(key, city);
                    inputQuery.setType("汽车维修|餐饮服务|生活服务|住宿服务");
                    Inputtips inputTips = new Inputtips(mContext, inputQuery);
                    try {
                        return inputTips.requestInputtips();
                    } catch (AMapException e) {
                        return new ArrayList<>();
                    }
                })
                .filter(tipList -> tipList.size() > 0)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(listener::onGetTips);
    }


    public void stop() {
        if (subscribe != null && !subscribe.isDisposed()) {
            subscribe.dispose();
            subscribe = null;
        }
    }

    public interface OnTipsListener {
        void onGetTips(List<Tip> list);
    }
}
